package com.muyu.chat.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.muyu.chat.websocket.WebSocketServer;
import com.muyu.chat.doamin.ChatMessage;
import com.muyu.chat.mapper.MessageMapper;
import com.muyu.chat.service.MessageService;
import com.muyu.chat.utils.Time;
import com.muyu.chat.utils.UploadFile;
import com.muyu.common.core.domain.Result;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 聊天的service
 *
 * */

@Service
@Slf4j
public class MessageServiceImpl implements MessageService {

    @Resource
    private MessageMapper messageMapper;

    /**
     * 获取聊天好友信息
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Map<String, Object> getFriendMsgList(Long userId, int pageNum, int pageSize) {
        Map<String,Object> resData = new HashMap<>();
        PageHelper.startPage(pageNum,pageSize);
        PageInfo<ChatMessage> info = new PageInfo<>(messageMapper.getFriendMsgList(userId));
        resData.put("pagesNum",info.getPages());
        resData.put("totalNum",info.getTotal());
        resData.put("size",info.getSize());
        resData.put("data", info.getList());
        return resData;
    }

    /**
     * 获取聊天信息
     * @param sendUserId
     * @param acceptUserId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Map<String, Object> getChatMessage(Long sendUserId,Long acceptUserId,int pageNum,int pageSize) {
        Map<String,Object> resData = new HashMap<>();
        PageHelper.startPage(pageNum,pageSize);
        List<ChatMessage> chatMessage = messageMapper.getChatMessage(sendUserId, acceptUserId);
        PageInfo<ChatMessage> info = new PageInfo<>(chatMessage);
        resData.put("pagesNum",info.getPages());
        resData.put("totalNum",info.getTotal());
        resData.put("size",info.getSize());
        resData.put("data", info.getList());
        return resData;
    }

    /**
     * 发送消息
     * @param chatMessage
     * @return
     */
    @Override
    public Map<String,Object> sendMsg(ChatMessage chatMessage) {
        Map<String,Object> repData = new HashMap<>();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        int identification = 0; // 默认值
        if (loginUser.getUserid().equals(chatMessage.getSendUserId())) {
            identification = 1; // 如果相等，设置为1
        } else {
            identification = 2;
        }
        chatMessage.setSendUserId(loginUser.getUserid());
        chatMessage.setType("text");
        if(messageMapper.sendMsg(chatMessage.getSendUserId(), chatMessage.getAcceptUserId(), chatMessage.getContent(), chatMessage.getType(), chatMessage.getSoundTime(), Time.getTime("yyyy-MM-dd HH:mm:ss"),identification)) {
            try {
                List<Map<String,Object>> newMsg = (List<Map<String, Object>>) this.getChatMessage(chatMessage.getSendUserId(), chatMessage.getAcceptUserId(),1,1).get("data");
                repData.put("status",true);
                repData.put("returnMsg",newMsg.get(0));
            }catch (Exception e){
                repData.put("status",false);
            }
        }
        return repData;
    }
    /**
     * 发送聊天文件
     * @param sendUserId
     * @param acceptUserId
     * @param type
     * @param file
     * @return
     */
    @Override
    public Map<String, Object> sendFileMsg(Long sendUserId, Long acceptUserId, String type, Integer time, MultipartFile file) {
        Map<String,Object> repData = new HashMap<>();
        Map<String,Object> res = UploadFile.doRemoteUpload(file,"/file/");
        if ((Boolean) res.get("status")) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            int identification = 0; // 默认值
            if (loginUser.getUserid().equals(sendUserId)) {
                identification = 1; // 如果相等，设置为1
            } else {
                identification = 2;
            }
            if (messageMapper.sendMsg(sendUserId,acceptUserId,(String) res.get("fileUrl"),type,time, Time.getTime("yyyy-MM-dd HH:mm:ss"),identification)) {
                List<Map<String,Object>> newMsg = (List<Map<String, Object>>) this.getChatMessage(sendUserId,acceptUserId,1,1).get("data");
//                try {
//
//                    webSocketServer.send(sendUserId, acceptUserId, newMsg.get(0));
//                }catch (IOException e) {
//                    log.info("发送失败！");
//                }
                repData.put("status",true);
                repData.put("returnMsg",newMsg.get(0));
            }
        }else {
            repData.put("status",false);
        }
        return repData;
    }

    /**iu i
     * 已读消息
     * @param sendUserId
     * @param acceptUserId
     * @return
     */
    @Override
    public Boolean readedMsg(Long sendUserId, Long acceptUserId) {
        return messageMapper.readedMsg(sendUserId,acceptUserId);
    }

    /**
     * 所有未读数
     * @param acceptUserId
     * @return
     */
    @Override
    public int getAllNoReadMsgNum(Long acceptUserId) {
        return messageMapper.getAllNoReadMsgNum(acceptUserId);
    }



}
